package com.sf.fy.uav.applet.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.sf.fy.uav.common.request.operate.OrderInfoReq;
import com.sf.fy.uav.common.response.order.task.DistributionOrderListRes;
import com.sf.fy.uav.common.utils.PhoneEncoderUtil;
import com.sf.fy.uav.common.utils.RespJsonPageData;
import com.sf.fy.uav.order.controller.OrderInfoRest;
import com.sf.fy.uav.order.entity.OrderInfo;
import com.sf.fy.uav.user.entity.User;
import com.sf.fy.uav.user.rest.UserRest;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author ta136817
 */
@RestController
@RequestMapping("/sys/distribution/")
@RequiredArgsConstructor
public class DistributionOrderListController {
    private final static Logger logger = LoggerFactory.getLogger(DistributionOrderListController.class);

    private final OrderInfoRest orderInfoRest;

    private final PhoneEncoderUtil phoneEncoderUtil;

    private final UserRest userRest;

    private final static Integer PLAT_FORM_CODE = 4;

    @GetMapping("get-order-list")
    @Operation(tags = "订单查询", description = "订单查询")
    public RespJsonPageData<DistributionOrderListRes> getOrderList(@RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) Integer platformCode, @RequestParam Integer orderInquiryEntry, @RequestParam(required = false) String tcWayBillNo, @RequestParam(required = false) Integer orderStatus, @RequestParam(required = false) String orderStartDate, @RequestParam(required = false) String orderEndDate, @RequestParam(required = false) String phoneNumber, @RequestParam(required = false) String thirdPartyOrderNumber, @RequestParam(required = false) String senderTel, @RequestParam(required = false) String receiverTel, @RequestParam(required = false) Boolean exportOrNot) {
        OrderInfoReq orderInfoReq = new OrderInfoReq();
        orderInfoReq.setPage(page);
        orderInfoReq.setSize(size);
        orderInfoReq.setTcWayBillNo(tcWayBillNo);
        orderInfoReq.setOrderStatus(orderStatus);
        orderInfoReq.setPhoneNumber(phoneNumber);
        orderInfoReq.setPlatformCode(platformCode);
        orderInfoReq.setOrderInquiryEntry(orderInquiryEntry);
        orderInfoReq.setThirdPartyOrderNumber(thirdPartyOrderNumber);
        orderInfoReq.setExportOrNot(exportOrNot);
        orderInfoReq.setSenderTel(senderTel);
        orderInfoReq.setReceiverTel(receiverTel);
        orderInfoReq.setOrderStartDate(orderStartDate);
        orderInfoReq.setOrderEndDate(orderEndDate);
        return orderInfoRest.getOrderList(orderInfoReq);
    }

    @GetMapping("export")
    @Operation(tags = "导出", description = "导出")
    @CrossOrigin
    public void export(HttpServletResponse response, @RequestParam Integer page, @RequestParam Integer size, @RequestParam Integer orderInquiryEntry, @RequestParam(required = false) String tcWayBillNo, @RequestParam(required = false) Integer orderStatus, @RequestParam(required = false) String orderStartDate, @RequestParam(required = false) String orderEndDate, @RequestParam(required = false) String phoneNumber, @RequestParam(required = false) String thirdPartyOrderNumber, @RequestParam(required = false) String senderTel, @RequestParam(required = false) String receiverTel, @RequestParam(required = false) Boolean exportOrNot) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            String fileName = "月结平台订单明细表" + sdf.format(new Date());
            response.setHeader("content-disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8) + ".xls");
            ExportParams exportParams = new ExportParams();
            RespJsonPageData<DistributionOrderListRes> orderListPage = this.getOrderList(page, size, PLAT_FORM_CODE, orderInquiryEntry, tcWayBillNo, orderStatus, orderStartDate, orderEndDate, phoneNumber, thirdPartyOrderNumber, senderTel, receiverTel, true);
            System.out.println(orderListPage.getResponseData());
            for (DistributionOrderListRes distributionOrderRes : orderListPage.getResponseData()) {
                if (ObjectUtils.allNotNull(distributionOrderRes.getPricePaid()) && distributionOrderRes.getPricePaid().compareTo(BigDecimal.ZERO) > 0) {
                    distributionOrderRes.setPricePaid(distributionOrderRes.getPricePaid().setScale(2, RoundingMode.UP));
                }
                if (ObjectUtils.allNotNull(distributionOrderRes.getPricePayable()) && distributionOrderRes.getPricePayable().compareTo(BigDecimal.ZERO) > 0) {
                    distributionOrderRes.setPricePayable(distributionOrderRes.getPricePayable().setScale(2, RoundingMode.UP));
                }
            }
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, DistributionOrderListRes.class, orderListPage.getResponseData());
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @GetMapping("get-decode-phone")
    @Operation(tags = "手机号解密", description = "手机号解密")
    public String getDecodePhone(@RequestParam String tcWayBillNo, @RequestParam String phoneKeyWord, @RequestParam(required = false) Integer platformCode) {
        OrderInfo orderInfo = orderInfoRest.getOrderInfoByTcWaybillNoAndPlatformCode(tcWayBillNo, platformCode);
        if (ObjectUtils.isEmpty(orderInfo)) {
            throw new RuntimeException("查无此订单!");
        }
        if (StringUtils.isNotBlank(phoneKeyWord) && phoneKeyWord.equals("receiverTel")) {
            return phoneEncoderUtil.decryptString(orderInfo.getReceiverTel());
        }
        if (StringUtils.isNotBlank(phoneKeyWord) && phoneKeyWord.equals("senderTel")) {
            return phoneEncoderUtil.decryptString(orderInfo.getSenderTel());
        }
        User normalUser = userRest.getNormalUser(orderInfo.getUserId());
        if (!ObjectUtils.isEmpty(normalUser) && StringUtils.isNotBlank(phoneKeyWord) && phoneKeyWord.equals("phoneNumber")) {
            return phoneEncoderUtil.decryptString(normalUser.getPhoneNumber());
        }
        return null;
    }
}
